package com.ecgsystem.thread;

import android.util.Log;
import java.io.*;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.StringTokenizer;

import com.ecgsystem.activity.OnlineECG;
import com.ecgsystem.constants.Commons;

public class TCPClient extends Thread {

	private String serverMess;
	StringTokenizer receivedMess;

	PrintWriter out;
	BufferedReader in;

	private String mess;

	/**
	 * Constructor of the class. OnMessagedReceived listens for the messages
	 * received from server
	 */
	public TCPClient(String mess) {
		this.mess = mess;
		OnlineECG.flag = false;
	}

	/**
	 * Sends the message entered by client to the server
	 * 
	 * @param message
	 *            text entered by client
	 */
	public void stopClient() {
	}

	@Override
	public void run() {

		try {
			// here you must put your computer's IP address.
			InetAddress serverAddr = InetAddress
					.getByName(Commons.UDP_SERVER_ADDRESS);

			Log.e("TCP Client", "C: Connecting..." + Commons.UDP_SERVER_ADDRESS);

			// create a socket to make the connection with the server
			Socket socket = new Socket(serverAddr, Commons.TCP_PORT);

			try {
				// send the message to the server
				out = new PrintWriter(new BufferedWriter(
						new OutputStreamWriter(socket.getOutputStream())), true);

				out.print(mess);
				out.flush();
				Log.d("TCP Client", "C: Sent.");

				Log.d("TCP Client", "C: Done.");

				in = new BufferedReader(new InputStreamReader(
						socket.getInputStream()));

				serverMess = in.readLine();
				receivedMess = new StringTokenizer(serverMess, "|#");
				String code = receivedMess.nextToken();
				if (code.equals("OK")) {
					OnlineECG.patientNo = Integer.valueOf(receivedMess
							.nextToken());
					String flag;
					Commons.LEADCOUNT = 0;
					for (int i = 0; i < 12; i++) {
						flag = receivedMess.nextToken();
						if (flag.equals("1")) {
							Commons.hasRecord[i] = true;
							Commons.LEADCOUNT++;
						}
					}
					Log.d("OK", "" + OnlineECG.patientNo);
					OnlineECG.flag = true;
				} else if (code.equals("NoWorkStation")) {
					ThreadGetSignal._run = false;
					Commons.NO_WORKSTATION = true;
					OnlineECG.displayAlert("Benh nhan hien tai khong duoc do.");
				} else if (code.equals("StopSend")) {
					OnlineECG.StopDraw();
					ThreadGetSignal._run = false;
					Commons.STOP_SEND_FLAG = true;
					OnlineECG.displayAlert("Ngung do");
				} else if (code.equals("ConnectionError")) {
					OnlineECG.StopDraw();
					ThreadGetSignal._run = false;
					OnlineECG.displayAlert("Loi ket noi server TCP");
				} else {
					OnlineECG.displayAlert("Loi ket noi server TCP");
				}

				Log.e("RESPONSE FROM SERVER", "S: Received Message: '"
						+ serverMess + "'");

			} catch (NullPointerException e) {
				OnlineECG.displayAlert("Loi ket noi server TCP");
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
				OnlineECG.displayAlert("Loi ket noi server TCP");
			} finally {
				// the socket must be closed. It is not possible to reconnect to
				// this socket
				// after it is closed, which means a new socket instance has to
				// be created.
				socket.close();
			}

		} catch (ConnectException e) {
			e.printStackTrace();
			OnlineECG.displayAlert("Loi ket noi server TCP");
		} catch (Exception e) {
			e.printStackTrace();
			OnlineECG.displayAlert("Loi ket noi server TCP");
		}
	}

}